﻿using System.Threading.Tasks;
using SmartCity.Shared;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace CommonManagement
{
    /// <summary>
    /// 账户应用服务类
    /// </summary>W
    public class AccountAppService : ApplicationService, IAccountAppService
    {
        private readonly UserManager _userManager;
        private readonly IAuthManager _authManager;
        private readonly IRepository<User, int> _userRepository;

        public AccountAppService(
            UserManager userManager,
            IAuthManager authManager,
            IRepository<User, int> userRepository)
        {
            _userManager = userManager;
            _authManager = authManager;
            _userRepository = userRepository;
        }

        // 登录
        public async Task<LoginResponse> LoginAsync(LoginDto input)
        {
            // 查询用户
            var user = await _userRepository.SingleOrDefaultAsync(m => m.UserName == input.UserName);
            if (user == null)
                return LoginResponse.NotFound(input.UserName);
            if (!user.Password.Equals(input.Password))
                return LoginResponse.Mismatch();
            // 创建票据
            var token = _authManager.GenerateToken(user.Id);
            // 返回结果
            var result = LoginResponse.Successful(token);
            return result;
        }

        // 注册
        public async Task<RegisterResponse> RegisterAsync(RegisterDto input)
        {
            try
            {
                await _userManager.CreateAsync(
                input.UserName,
                input.Password,
                input.Avatar,
                input.NickName,
                input.Sex,
                input.Phonenumber,
                input.Email,
                input.IdCard);
                return RegisterResponse.Successful();
            }
            catch (UserNameAlreadyExistsException)
            {
                return RegisterResponse.Registered(input.UserName);
            }
        }
    }
}